import java.io.*;
import java.net.*;

class UDPServer {
    int portnumber;

    UDPServer(int portnumber) {
        this.portnumber = portnumber;
    }

    public void run() throws Exception {
        DatagramSocket serverSocket = new DatagramSocket(portnumber);
        byte[] receiveData = new byte[1024];
        byte[] sendData = new byte[1024];
        while (true) {
            DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
            serverSocket.receive(receivePacket);

            receiveData = receivePacket.getData();

            String tempSentence = new String(receiveData);
            String sentence = tempSentence.replaceAll("\u0000", "");   //hreinsa strenginn sem kom inn


            System.out.println("RECEIVED: " + sentence);              // birtir á server hvaða strengur kom inn
            InetAddress IPAddress = receivePacket.getAddress();
            int port = receivePacket.getPort();


            char[] stringArray = sentence.toCharArray();    // brjóta upp strenginn
            if (Character.isDigit(stringArray[0])) {        // ef fyrsta táknið er tölustafur þá leggjum við tölurnar saman

                String[] arr = sentence.split(" ", 3);

                int sum = Integer.parseInt(arr[0]) + Integer.parseInt(arr[1]);
                sendData = ("numbers added = " + sum).getBytes();

            } else {                                                      //ef fyrsti stafurinn er bókstafur þá skoðum við hvaða texti var sendur

                if ((sentence.contains("jvm")) || (sentence.contains("JVM"))) {  // ef notandi skrifaði jvm fær hann upplýsingar um JVM memory
                    int megaBytes = 1024 * 1024;
                    Runtime runtime = Runtime.getRuntime();
                    String s = ("Used Memory: "
                            + ((runtime.totalMemory() - runtime.freeMemory()) / megaBytes)) + "\r\n"

                            + ("Free Memory: "
                            + runtime.freeMemory() / megaBytes) + "\r\n"
                            + ("Total Memory: "
                            + runtime.totalMemory() / megaBytes) + "\r\n"
                            + ("Max Memory: "
                            + runtime.maxMemory() / megaBytes) + "\r\n";

                    sendData = s.getBytes();
                } else {                                                        // ef notandi skrifaði e-ð annað en jvm þá skilum við textanum í hástöfum
                    String capitalizedSentence = sentence.toUpperCase();
                    sendData = capitalizedSentence.getBytes();
                }
            }


            DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, port);
            serverSocket.send(sendPacket);                                    // það sem við sendum til baka
        }
    }
}

